//
//  MSRequestQueue.m
//  Musou
//
//  Created by danal on 13-3-18.
//
//

#import "MSRequestObjectQueue.h"

@implementation MSRequestObjectQueue
@synthesize delegate = _delegate;

- (void)dealloc{
    [_requestList release];
    [super dealloc];
}

- (id)init{
    self = [super init];
    if (self) {
        _requestList = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)addRequestObject:(MSRequestObject *)rqo{
    [_requestList addObject:rqo];
}

//Start the queue
- (void)start{
    _started = YES;
    _index = 0;
    [self runNext];
}

//Break the queue
- (void)cancel{
    self.delegate = nil;
    MSRequestObject *rqo = [_requestList objectAtIndex:_index];
    [rqo cancel];
}

//Run a request
- (void)runNext{
    MSRequestObject *rqo = [_requestList objectAtIndex:_index];
    [rqo start];
}

#pragma mark - MSRequestObjectDelegate

- (void)onRequestStart:(MSRequestObject *)rqo{
    if (_index == 0) {
        if (_delegate && [_delegate respondsToSelector:@selector(onRequestQueueStart:)]) {
            [_delegate onRequestQueueStart:self];
        }
    }
}

- (void)onRequestComplete:(MSRequestObject *)rqo error:(NSError *)error{
    
    if (_index == [_requestList count] - 1) {
        if (_delegate) {
            [_delegate onRequestQueueEnd:self];
        }
    }
    else {
        if (_delegate) {
            [_delegate onRequestQueueFinishOne:[_requestList objectAtIndex:_index] ofQueue:self];
        }
        _index++;
        [self runNext];
    }
}

@end
